<template>
  <div class="common-layout">
    <el-container>
      <el-header style="border-style: groove;border-width: 2px;margin-bottom: 10px;">
          <el-form :inline="true" style="margin-top: 10px;">
              <el-form-item label="商品名称">
              <el-input v-model="q.productName" />
            </el-form-item>
             <el-form-item label="商品状态">
            <el-radio-group v-model="q.allocationStatus">
              <el-radio :value="1">出库</el-radio>
              <el-radio :value="2">入库</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item >
              <el-button @click="show" type="primary">搜索</el-button>
              <el-button @click="chongzhi" type="info">重置</el-button>
            </el-form-item>
          </el-form>
      </el-header>
      <el-main style="border-style: groove;border-width: 2px;margin-bottom: 10px;height: 590px;">
        <el-button type="success" style="margin-bottom: 10px;" @click="open(null)">新增</el-button>
          <el-table :data="tableData" border style="width: 100%">
    <el-table-column type="index" label="编号"/>
    <el-table-column prop="inventoryTransferOrder" label="调拨单号">
      <template v-slot="scope">
        <el-link 
          type="primary" 
          :underline="false"
          @click="goToDetail(scope.row.inventoryTransferOrder)"
        >
          {{ scope.row.inventoryTransferOrder }}
        </el-link>
      </template>
    </el-table-column>
    <el-table-column prop="allocationTime" label="调拨日期" >
      <template v-slot="scope">
          {{ moment(scope.row.allocationTime) .format("YYYY-MM-DD")}}
      </template>
    </el-table-column>
    <el-table-column prop="allocationStatus" label="调拨类型">
      <template v-slot="scope">
        <el-tag v-if="scope.row.allocationStatus==1">货品调拨</el-tag>
        <el-tag v-if="scope.row.allocationStatus==2">库存预警</el-tag>
        <el-tag v-if="scope.row.allocationStatus==3">满仓调离</el-tag>
        <el-tag v-if="scope.row.allocationStatus==4">其他调拨</el-tag>
      </template>
    </el-table-column>
    <el-table-column prop="productName" label="商品名称"/>
    <el-table-column prop="unit" label="单位"/>
    <el-table-column prop="specificationModel" label="规格" />
    <el-table-column prop="num" label="调拨数量"/>
    <el-table-column prop="transferReasons" label="调拨原因" />
    <el-table-column prop="expectedTime" label="预期完成时间" >
      <template v-slot="scope">
          {{ moment(scope.row.expectedTime) .format("YYYY-MM-DD")}}
      </template>
    </el-table-column>
    <el-table-column prop="jingBanName" label="审批人名称"/>
    <el-table-column  label="操作列" width="220">
        <template v-slot="scope">
          <el-button type="danger"  size="small" @click="del(scope.row)">删除</el-button>
          <el-button type="primary" size="small" @click="fantian(scope.row),getmingxidata(scope.row.inventoryId)">修改</el-button>
        </template>
    </el-table-column>
  </el-table>
  <table>
            <el-pagination
            v-model:current-page="p.index"
            v-model:page-size="p.size"
            :page-sizes="[15, 16, 17, 18]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="p.count"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            />
        </table>
      </el-main>
    </el-container>
  </div>

<el-dialog v-model="logic.isopen" :title="logic.title" width="1200" align-center draggable>
    <el-form :model="form">
      <el-form-item label="调拨单号" :label-width="formLabelWidth">
        <el-input  autocomplete="off" v-model="form.inventoryTransferOrder" :readonly="logic.isadd"/>
      </el-form-item>
      <el-form-item label="调拨时间" :label-width="formLabelWidth">
      <el-col :span="11">
        <el-date-picker
          v-model="form.allocationTime"
          type="date"
          placeholder="选择时间"
          style="width: 100%"
        />
      </el-col>
    </el-form-item>
      <el-form-item label="调拨类型" :label-width="formLabelWidth">
        <el-select  placeholder="请选择" v-model="form.allocationStatus">
          <el-option label="货品调拨" :value="1" />
          <el-option label="库存预警" :value="2" />
          <el-option label="满仓调离" :value="3" />
          <el-option label="其他调拨" :value="4" />
        </el-select>
      </el-form-item>
      <el-form-item label="调出仓库" :label-width="formLabelWidth">
        <el-select  
          placeholder="请选择" 
          v-model="form.chuId"
          :disabled="!!form.ruId"
          @change="handleChuChange"
        >
          <el-option v-for="item in chudata" :label="item.outboundProductName" :value="item.chuId"/>
        </el-select>
      </el-form-item>
       <el-form-item label="调入仓库" :label-width="formLabelWidth">
        <el-select  
          placeholder="请选择" 
          v-model="form.ruId"
          :disabled="!!form.chuId"
          @change="handleRuChange"
          :clearable="!form.chuId"
        >
          <el-option v-for="item in rudata" :label="item.inboundProductName" :value="item.ruId"/>
        </el-select>
      </el-form-item>
      <el-form-item label="调拨原因" :label-width="formLabelWidth">
        <el-input  autocomplete="off" v-model="form.transferReasons"/>
    </el-form-item>
    </el-form>

    <!-- 调拨明细表格 -->
    <div class="mingxi-container">
      <div class="mingxi-header">
        <h3>调拨明细</h3>
        <div class="action-buttons">
          <el-button type="success" @click="dialogFormVisible = true">新增</el-button>
          <!-- <el-button type="primary" @click="addMingxiItem">新增行</el-button> -->
          <el-button type="danger" @click="removeMingxiItem">移除</el-button>
        </div>
      </div>
      
      <el-table :data="mingxiData" border style="width: 100%">
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column prop="shopId" label="ShopId" />
        <el-table-column prop="productName" label="货品名称" />
        <el-table-column prop="productCode" label="货品编号" />
        <el-table-column prop="specificationModel" label="规格型号" />
        <el-table-column prop="unit" label="单位" />
        <el-table-column prop="goodsType" label="货品类型" />
        <el-table-column prop="originalInventory" label="原库存数量" width="120" />
        <el-table-column label="* 调拨数量" width="150">
          <template v-slot="scope">
            <el-input 
              v-model="scope.row.allocationQuantity" 
              placeholder="请输入数量"
              @input="calculateAmount(scope.$index)"
            />
          </template>
        </el-table-column>
        <el-table-column label="计算后库存" width="120">
          <template v-slot="scope">
            <span :style="{ color: getInventoryColor(scope.row) }">
              {{ calculateInventory(scope.row) }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="unitPrice" label="入库单价" />
        <el-table-column prop="allocationAmount" label="调拨金额" />
        <el-table-column label="操作" width="100">
          <template v-slot="scope">
            <el-link type="danger" @click="removeItem(scope.$index)">移除</el-link>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 合计信息 -->
      <div class="summary-info">
        <span class="summary-label">合计</span>
        <div class="summary-stats">
          <span>调拨种类: {{ mingxiData.length }}</span>
          <span>调拨数量: {{ totalQuantity }}</span>
          <span>调拨金额: {{ totalAmount }}</span>
        </div>
      </div>
   
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="logic.isopen = false">取消</el-button>
        <el-button type="primary" @click="save">
          完成
        </el-button>
      </div>
    </template>
  </el-dialog>



  <el-dialog v-model="xiugaiisopen" :title="logic.title" width="1200" align-center draggable>
    <el-form :model="form">
      <el-form-item label="调拨单号" :label-width="formLabelWidth">
        <el-input  autocomplete="off" v-model="form.inventoryTransferOrder"/>
      </el-form-item>
      <el-form-item label="调拨时间" :label-width="formLabelWidth">
      <el-col :span="11">
        <el-date-picker
          v-model="form.allocationTime"
          type="date"
          placeholder="选择时间"
          style="width: 100%"
        />
      </el-col>
    </el-form-item>
      <el-form-item label="调拨类型" :label-width="formLabelWidth">
        <el-select  placeholder="请选择" v-model="form.allocationStatus">
          <el-option label="货品调拨" :value="1" />
          <el-option label="库存预警" :value="2" />
          <el-option label="满仓调离" :value="3" />
          <el-option label="其他调拨" :value="4" />
        </el-select>
      </el-form-item>
      <el-form-item label="调出仓库" :label-width="formLabelWidth">
        <el-select  
          placeholder="请选择" 
          v-model="form.chuId"
          :disabled="!!form.ruId"
          @change="handleChuChange"
        >
          <el-option v-for="item in chudata" :label="item.outboundProductName" :value="item.chuId"/>
        </el-select>
      </el-form-item>
       <el-form-item label="调入仓库" :label-width="formLabelWidth">
        <el-select  
          placeholder="请选择" 
          v-model="form.ruId"
          :disabled="!!form.chuId"
          @change="handleRuChange"
          :clearable="!form.chuId"
        >
          <el-option v-for="item in rudata" :label="item.inboundProductName" :value="item.ruId"/>
        </el-select>
      </el-form-item>
      <el-form-item label="调拨原因" :label-width="formLabelWidth">
        <el-input  autocomplete="off" v-model="form.transferReasons"/>
    </el-form-item>
    </el-form>

    <!-- 调拨明细表格 -->
    <div class="mingxi-container">
      <div class="mingxi-header">
        <h3>调拨明细</h3>
        <div class="action-buttons">
          <!-- <el-button type="primary" @click="addMingxiItem">新增行</el-button> -->
          <el-button type="danger" @click="removeMingxiItem">移除</el-button>
        </div>
      </div>
      
       <el-table :data="mingxiData" border style="width: 100%">
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column prop="productName" label="货品名称" />
        <el-table-column prop="productNumber" label="货品编号" />
        <el-table-column prop="specificationModel" label="规格型号" />
        <el-table-column prop="unit" label="单位" />
        <el-table-column prop="goodsType" label="货品类型" />
        <el-table-column prop="num" label="* 调拨数量" width="150">
        </el-table-column>
        <el-table-column prop="price" label="入库单价" />
        <el-table-column prop="jinPrice" label="调拨金额" />
        <el-table-column label="操作" width="100">
          <template v-slot="scope">
            <el-link type="danger" @click="removeItem(scope.$index)">移除</el-link>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 合计信息 -->
      <div class="summary-info">
        <span class="summary-label">合计</span>
        <div class="summary-stats">
          <span>调拨种类: {{ mingxiData.length }}</span>
          <span>调拨数量: {{ totalQuantity }}</span>
          <span>调拨金额: {{ totalAmount }}</span>
        </div>
      </div>
   
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="logic.isopen = false">取消</el-button>
        <el-button type="primary" @click="xiugai()">
          完成
        </el-button>
      </div>
    </template>
  </el-dialog>



  <el-dialog v-model="dialogFormVisible" title="添加货品" width="800">
    <!-- 搜索区域 -->
    <div class="search-area">
      <el-form :inline="true" style="margin-top: 10px;">
              <el-form-item label="商品名称">
              <el-input v-model="query.productName" />
            </el-form-item>
             <el-form-item label="商品单位">
            <el-radio-group v-model="query.unit">
              <el-radio value="箱">箱</el-radio>
              <el-radio value="瓶">瓶</el-radio>
              <el-radio value="个">个</el-radio>
              <el-radio value="台">台</el-radio>
              <el-radio value="条">条</el-radio>
              <el-radio value="包">包</el-radio>
              <el-radio value="支">支</el-radio>
              <el-radio value="部">部</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item >
              <el-button @click="showShop" type="primary">搜索</el-button>
              <el-button @click="chongzhishop" type="info">重置</el-button>
              <el-button @click="showSelectedIds" type="warning">显示选择ID</el-button>
            </el-form-item>
          </el-form>
    </div>

    <!-- 商品列表表格 -->
    <el-table 
      :data="productList" 
      border 
      style="width: 100%; margin-top: 15px;"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column type="index" label="序号" width="60" />
      <el-table-column prop="shopId" label="ShopId" width="80" />
      <el-table-column prop="productNumber" label="货品编号" width="120" />
      <el-table-column prop="productName" label="货品名称" width="150" />
      <el-table-column prop="specificationModel" label="规格型号" width="100" />
      <el-table-column prop="unit" label="单位" width="80" />
      <el-table-column prop="transferQuantity" label="入库单价" width="100" />
      <el-table-column prop="kuCunNum" label="库存数量" width="100" />
      <el-table-column prop="inboundUnitPrice" label="金额" width="100" />
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container" style="margin-top: 15px; display: flex; justify-content: space-between; align-items: center;">
      <span>总{{ productTotal }}条</span>
      <el-pagination
        v-model:current-page="productPagination.currentPage"
        v-model:page-size="productPagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="productTotal"
        layout="sizes, prev, pager, next, jumper"
        @size-change="handleProductSizeChange"
        @current-change="handleProductCurrentChange"
      />
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmAddProducts">确定</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script lang="ts" setup>
import axios from 'axios';
import { ElMessage, ElMessageBox } from 'element-plus';
import moment from 'moment';
import { onMounted, reactive, ref, computed, nextTick, watch } from 'vue';
import { useRouter } from 'vue-router';
const formLabelWidth = '140px'
const router = useRouter();
const tableData =ref([])
const dialogFormVisible = ref(false)
const xiugaiisopen=ref(false)
// 新增商品弹框相关数据
const searchForm = reactive({
  productKeyword: '',
  unit: ''
})
const fantian=(row:any)=>{
  xiugaiisopen.value=true;
  form.inventoryId=row.inventoryId
  form.inventoryTransferOrder=row.inventoryTransferOrder
  form.allocationTime=row.allocationTime
  form.chuId=row.chuId
  form.ruId=row.ruId
  form.allocationStatus=row.allocationStatus
  form.transferReasons=row.transferReasons
  form.jingBanName=row.jingBanName
  form.shopId=row.shopId
}

const xiugai=()=>{
  xiugaiisopen.value=true;
  axios.post("http://8.152.103.143:5001/api/Manangement/UpdInventoryAllocation",form)
  .then(res=>{
    if(res.data.code==400)
  {
    ElMessage.success(res.data.message);
    xiugaiisopen.value=false;
  }
  else
  {
    ElMessage.error(res.data.message);
  }
  })
}
const query=reactive({
  productName:'',
  unit:''
})
const chongzhishop=()=>{
  query.productName='',
  query.unit=''
}
const productList = ref([
])
const showShop=()=>{
  axios.get("http://8.152.103.143:5000/api/Management/GetShop",{params:{
    index:productPagination.currentPage,size:productPagination.pageSize,productName:query.productName,unit:query.unit
  }})
  .then(res=>{
    console.log('=== 商品列表API响应 ===');
    console.log('响应数据:', res.data);
    console.log('商品列表:', res.data.data.list);
    if (res.data.data.list && res.data.data.list.length > 0) {
      console.log('第一个商品数据结构:', res.data.data.list[0]);
      console.log('第一个商品的所有字段:', Object.keys(res.data.data.list[0]));
      // 查找可能的ID字段
      const firstProduct = res.data.data.list[0];
      const possibleIdFields = ['shopId', 'id', 'productId', 'goodsId', 'itemId'];
      possibleIdFields.forEach(field => {
        if (firstProduct.hasOwnProperty(field)) {
          console.log(`找到ID字段 ${field}:`, firstProduct[field]);
        }
      });
      
      // 特别检查shopId字段
      if (firstProduct.shopId !== undefined) {
        console.log('shopId字段存在，值:', firstProduct.shopId, '类型:', typeof firstProduct.shopId);
      } else {
        console.warn('shopId字段不存在，请检查API返回的数据结构');
      }
    }
    productList.value=res.data.data.list;
    productTotal.value=res.data.data.totalCount;
    productPagination.currentPage=res.data.data.currentPage || 1;
  })
}
const productTotal = ref(100)
const productPagination = reactive({
  currentPage: 1,
  pageSize: 10
})

const selectedProducts = ref<any[]>([])
const selectedProductIds = ref<number[]>([]) // 存储被选择的商品ID数组
const mingxiData = ref<any[]>([])
const getmingxidata=(inventoryId:any)=>{
  axios.get("http://8.152.103.143:5000/api/Management/GetInventoryIdXiangqing",{params:{
    inventoryId:inventoryId
  }})
  .then(res=>{
    mingxiData.value=res.data.data;
  })
}

// 跳转到详情页面的方法
const goToDetail = (inventoryTransferOrder: any) => {
  router.push({path:"/Xiangqing",query:{inventoryTransferOrder:inventoryTransferOrder}})
};

onMounted(()=>{
  show()
  getChu();
  getRu();
  showShop();
  //getmingxidata();
})
const p=reactive({
  index:1,
  size:15,
  pcount:0,
  count:0
})
const q=reactive({
  productName:'',
  allocationStatus:0
})
const show=()=>{
  axios.get("http://8.152.103.143:5000/api/Management/GetInventory",{params:{
    index:p.index,size:p.size,productName:q.productName,allocationStatus:q.allocationStatus
  }})
  .then(res=>{
    tableData.value=res.data.data.list;
    p.count=res.data.data.totalCount;
    p.pcount=res.data.data.totalPage;
  })
}
const chongzhi=()=>{
  q.allocationStatus=0,
  q.productName=''
}
const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`)
  p.size=val;
  show();
}
const handleCurrentChange = (val: number) => {
  console.log(`current page: ${val}`)
  p.index=val;
  show();
}
const chudata=ref<any>([])
const getChu=()=>{
  axios.get("http://8.152.103.143:5000/api/Management/GetChuku")
  .then(res=>{
    chudata.value=res.data.data;
  })
}
const rudata=ref<any>([])
const getRu=()=>{
  axios.get("http://8.152.103.143:5000/api/Management/GetRuku")
  .then(res=>{
    rudata.value=res.data.data;
  })
}
const logic=reactive({
    isopen:false,
    title:'',
    isadd:false
})
const form = reactive({
  inventoryId: 0,
  inventoryTransferOrder: "",
  allocationTime: "",
  chuId: null,
  ruId: null,
  allocationStatus: null,
  transferReasons:'',
  jingBanName:'admin',
  shopId:''
})


// 移除明细项
const removeMingxiItem = () => {
  if (mingxiData.value.length > 0) {
    mingxiData.value.pop();
  }
}

// 移除指定项
const removeItem = (index: number) => {
  mingxiData.value.splice(index, 1);
}

// 计算金额
const calculateAmount = (index: number) => {
  const item = mingxiData.value[index];
  const quantity = parseFloat(item.allocationQuantity) || 0;
  item.allocationAmount = quantity * item.unitPrice;
  
  // 更新表单中的总数量
  const totalQuantity = mingxiData.value.reduce((total, item) => {
    const qty = parseFloat(item.allocationQuantity) || 0;
    return total + qty;
  }, 0);
  
  // 重新计算库存（如果已选择仓库类型）
  if (form.chuId || form.ruId) {
    updateInventoryCalculation(form.chuId ? 'outbound' : 'inbound');
  }
}

// 计算总数量和总金额
const totalQuantity = computed(() => {
  return mingxiData.value.reduce((total, item) => {
    const quantity = parseFloat(item.allocationQuantity) || 0;
    return total + quantity;
  }, 0);
})

const totalAmount = computed(() => {
  return mingxiData.value.reduce((total, item) => {
    return total + (item.allocationAmount || 0);
  }, 0);
})

const open = (row: any) => {
  if (row == null) {
    logic.isadd = true;
    logic.isopen = true;
    logic.title = "新增";
    // 自动生成调拨单号，以DB开头
    const timestamp = new Date().getTime();
    const randomNum = Math.floor(Math.random() * 1000).toString().padStart(3, '0');
    form.inventoryTransferOrder = `DB${timestamp}${randomNum}`;
    form.allocationTime= "";
    form.chuId=null;
    form.ruId=null;
    form.allocationStatus=null;
    form.transferReasons='';
    form.jingBanName='';
    form.shopId='';
    // 清空调拨明细数据
    mingxiData.value = [];
    selectedProducts.value = [];
    selectedProductIds.value = [];
  } else {
    logic.isadd = false;
    logic.isopen = true;
    logic.title = "编辑";
    form.inventoryId = row.inventoryId;
    form.inventoryTransferOrder = row.inventoryTransferOrder;
    form.allocationTime = row.allocationTime;
    form.chuId = row.chuId;
    form.ruId = row.ruId;
    form.allocationStatus = row.allocationStatus;
    form.transferReasons = row.transferReasons;
    form.jingBanName = row.jingBanName;
    form.shopId = row.shopId;

    // 反填调拨明细
    mingxiData.value = (row.xiangQings || []).map((item: any) => ({
      shopId: item.shopId ?? '', // 保证有值
      productName: item.productName ?? '',
      productCode: item.productNumber ?? '', // 货品编号
      specificationModel: item.specificationModel ?? '',
      unit: item.unit ?? '',
      goodsType: item.goodsType ?? '',
      originalInventory: item.kuCunNum ?? '', // 原库存数量
      allocationQuantity: item.num ?? '', // 调拨数量
      unitPrice: item.price ?? '',
      allocationAmount: item.jinPrice ?? ''
    }));
  }
};
const save=()=>{
  // 检查调拨明细是否为空
  if (mingxiData.value.length === 0) {
    ElMessage.warning('请先添加调拨明细商品');
    return;
  }

  // 检查必填字段
  if (!form.inventoryTransferOrder) {
    ElMessage.warning('调拨单号不能为空');
    return;
  }

  if (!form.allocationTime) {
    ElMessage.warning('调拨时间不能为空');
    return;
  }


  if (!form.allocationStatus) {
    ElMessage.warning('请选择调拨类型');
    return;
  }

  // 组装明细数据
  const xiangQings = mingxiData.value.map((item, index) => {
    const originalInventory = parseFloat(item.originalInventory) || 0;
    const allocationQuantity = parseFloat(item.allocationQuantity) || 0;
    let calculatedInventory = originalInventory;
    
    // 根据选择的仓库类型计算库存
    if (form.chuId) {
      // 出库：库存减少
      calculatedInventory = Math.max(0, originalInventory - allocationQuantity);
    } else if (form.ruId) {
      // 入库：库存增加
      calculatedInventory = originalInventory + allocationQuantity;
    }
    
    const detail = {
      id: 0,
      inventoryId: 0,
      productName: item.productName || '',
      productNumber: item.productCode || '',
      specificationModel: item.specificationModel || '',
      unit: item.unit || '',
      goodsType: item.goodsType || '',
      chuku: '',
      ruku: '',
      num: allocationQuantity,
      price: parseFloat(item.unitPrice) || 0,
      jinPrice: parseFloat(item.allocationAmount) || 0,
      stateChu: '',
      stateRu: '',
      originalInventory: originalInventory, // 原库存数量
      calculatedInventory: calculatedInventory // 计算后的库存数量
    };
    
    console.log(`明细${index + 1}:`, detail);
    return detail;
  });

  // 获取第一个商品的shopId作为主表的shopId
  const firstShopId = mingxiData.value.length > 0 ? mingxiData.value[0].shopId?.toString() || '' : '';

  // 处理时间格式，确保符合ISO 8601格式
  let formattedAllocationTime = '';
  if (form.allocationTime) {
    try {
      const date = new Date(form.allocationTime as any);
      if (!isNaN(date.getTime())) {
        formattedAllocationTime = date.toISOString();
      } else {
        formattedAllocationTime = form.allocationTime as string;
      }
    } catch (error) {
      formattedAllocationTime = form.allocationTime as string;
    }
  }

  // 组装主表数据
  const payload = {
    inventoryTransferOrder: form.inventoryTransferOrder,
    allocationTime: formattedAllocationTime,
    chuId: form.chuId ? parseInt(form.chuId as any) :0, // 如果没有选择调出仓库，默认为1
    ruId: form.ruId ? parseInt(form.ruId as any) : 0, // 如果没有选择调入仓库，默认为1
    allocationStatus: parseInt(form.allocationStatus as any) || 0,
    transferReasons: form.transferReasons || '',
    jingBanName: form.jingBanName || 'admin',
    shopId: firstShopId, // 新增shopId字段
    xiangQings
  };

  console.log('=== 提交的数据 ===');
  console.log('主表数据:', {
    inventoryTransferOrder: payload.inventoryTransferOrder,
    allocationTime: payload.allocationTime,
    chuId: payload.chuId,
    ruId: payload.ruId,
    allocationStatus: payload.allocationStatus,
    transferReasons: payload.transferReasons,
    jingBanName: payload.jingBanName,
    shopId: payload.shopId
  });
  console.log('明细数量:', xiangQings.length);
  console.log('完整数据:', payload);

  // 调用后端接口
  axios.post("http://8.152.103.143:5001/api/Manangement/AddInventoryAllocation", payload, {
    headers: {
      'Content-Type': 'application/json'
    }
  })
    .then(res => {
      console.log('=== 响应结果 ===');
      console.log('状态码:', res.status);
      console.log('响应数据:', res.data);
      
      if (res.data.code === 200) {
        ElMessage.success(res.data.message || '添加成功');
        logic.isopen = false;
        // 清空调拨明细数据
        mingxiData.value = [];
        // 清空选中的商品
        selectedProducts.value = [];
        selectedProductIds.value = [];
        show();
      } else {
        ElMessage.error(res.data.message || '添加失败');
      }
    })
    .catch(err => {
      console.error('=== 请求错误 ===');
      console.error('错误对象:', err);
      console.error('错误响应:', err.response?.data);
      console.error('错误状态:', err.response?.status);
      ElMessage.error('网络或服务器错误，添加失败');
    });
}
const del=(row:any)=>{
    ElMessageBox.confirm(
    '你确定删除吗?',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
        console.log(row);
        axios.post("http://8.152.103.143:5001/api/Manangement/DelInventoryAllocation",row)
        .then(res=>{
            if(res.data.code==300)
            {
                ElMessage.success(res.data.message);
                show();
            }
            else
            {
                ElMessage.error(res.data.message);
            }
        })
        .catch(error => {
            console.error('删除失败:', error);
            ElMessage.error('删除失败，请检查网络连接');
        })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '删除被取消',
      })
    })
}

// 新增商品弹框相关方法
const resetSearch = () => {
  searchForm.productKeyword = ''
  searchForm.unit = ''
  searchProducts()
}

const searchProducts = () => {
  // 这里可以调用API进行搜索，现在使用模拟数据
  console.log('搜索条件:', searchForm)
  // 实际项目中这里应该调用后端API
  // axios.get('/api/products', { params: searchForm })
}

const handleSelectionChange = (selection: any[]) => {
  console.log('=== 商品选择变化 ===');
  console.log('选中的商品数量:', selection.length);
  
  // 收集被选择的商品ID
  selectedProductIds.value = selection.map(product => parseInt(product.shopId) || 0);
  console.log('被选择的商品ID数组:', selectedProductIds.value);
  
  selection.forEach((product, index) => {
    console.log(`选中商品${index + 1}:`, {
      shopId: product.shopId,
      productName: product.productName,
      productNumber: product.productNumber
    });
  });
  selectedProducts.value = selection
}

const handleProductSizeChange = (val: number) => {
  productPagination.pageSize = val
  showShop()
}

const handleProductCurrentChange = (val: number) => {
  productPagination.currentPage = val
  showShop()
}

const confirmAddProducts = () => {
  if (selectedProducts.value.length === 0) {
    ElMessage.warning('请选择要添加的商品')
    return
  }
  
  console.log('=== 选中的商品 ===');
  console.log('被选择的商品ID数组:', selectedProductIds.value);
  
  selectedProducts.value.forEach((product, index) => {
    console.log(`商品${index + 1}:`, {
      shopId: product.shopId,
      productName: product.productName,
      productNumber: product.productNumber,
      productCode: product.productCode,
      specificationModel: product.specificationModel,
      unit: product.unit,
      transferQuantity: product.transferQuantity,
      inboundUnitPrice: product.inboundUnitPrice
    });
    console.log(`商品${index + 1} 完整数据:`, product);
  });
  
  // 将选中的商品添加到调拨明细中
  selectedProducts.value.forEach(product => {
    // 确保shopId存在且有效
    if (!product.shopId) {
      console.warn('商品缺少shopId:', product);
      ElMessage.warning(`商品 ${product.productName} 缺少商品ID，请检查数据`);
      return;
    }
    
    const newItem = {
      shopId: parseInt(product.shopId) || 0,
      productName: product.productName,
      productCode: product.productNumber, // 货品编号
      specificationModel: product.specificationModel,
      unit: product.unit,
      goodsType: '饮品',
      originalInventory: product.kuCunNum || 0, // 原库存数量
      allocationQuantity: '', // 新增时为空
      unitPrice: product.transferQuantity || product.inboundUnitPrice || 0,
      allocationAmount: 0
    }
    
    console.log('添加到调拨明细:', newItem);
    console.log('shopId类型:', typeof newItem.shopId, '值:', newItem.shopId);
    mingxiData.value.push(newItem)
  })
  
  ElMessage.success(`成功添加 ${selectedProducts.value.length} 个商品到调拨明细`)
  dialogFormVisible.value = false
  selectedProducts.value = []
  selectedProductIds.value = [] // 清空选择的ID数组
  
  // 自动更新表单信息
  updateFormFromMingxi()
  
  // 刷新商品列表
  showShop()
}

// 更新表单信息
const updateFormFromMingxi = () => {
  if (mingxiData.value.length > 0) {
    // 获取第一个商品的信息作为主要信息
    const firstProduct = mingxiData.value[0];
    // 计算总数量
    const totalQuantity = mingxiData.value.reduce((total, item) => {
      const quantity = parseFloat(item.allocationQuantity) || 0;
      return total + quantity;
    }, 0);
  }
}

// 监听调拨明细变化
watch(mingxiData, () => {
  updateFormFromMingxi();
}, { deep: true })

// 获取当前选择的商品ID数组
const getSelectedProductIds = () => {
  console.log('当前选择的商品ID数组:', selectedProductIds.value);
  return selectedProductIds.value;
}

// 测试方法：显示当前选择的商品ID
const showSelectedIds = () => {
  if (selectedProductIds.value.length > 0) {
    ElMessage.success(`当前选择的商品ID: ${selectedProductIds.value.join(', ')}`);
  } else {
    ElMessage.warning('当前没有选择任何商品');
  }
}

// 处理调出仓库选择变化
const handleChuChange = (value: any) => {
  if (value) {
    // 如果选择了调出仓库，清空调入仓库的值并禁用
    form.ruId = null;
    // 更新调拨明细中的库存计算
    updateInventoryCalculation('outbound');
  }
}

// 处理调入仓库选择变化
const handleRuChange = (value: any) => {
  if (value) {
    // 如果选择了调入仓库，清空调出仓库的值并禁用
    form.chuId = null;
    // 更新调拨明细中的库存计算
    updateInventoryCalculation('inbound');
  }
}

// 更新库存计算
const updateInventoryCalculation = (type: 'outbound' | 'inbound') => {
  mingxiData.value.forEach(item => {
    const originalInventory = parseFloat(item.originalInventory) || 0;
    const allocationQuantity = parseFloat(item.allocationQuantity) || 0;
    
    if (type === 'outbound') {
      // 出库：库存减少
      item.calculatedInventory = Math.max(0, originalInventory - allocationQuantity);
    } else {
      // 入库：库存增加
      item.calculatedInventory = originalInventory + allocationQuantity;
    }
  });
}

// 计算调拨后的库存数量
const calculateInventory = (item: any) => {
  const originalInventory = parseFloat(item.originalInventory) || 0;
  const allocationQuantity = parseFloat(item.allocationQuantity) || 0;
  
  // 根据选择的仓库类型计算库存
  if (form.chuId) {
    // 出库：库存减少
    return Math.max(0, originalInventory - allocationQuantity);
  } else if (form.ruId) {
    // 入库：库存增加
    return originalInventory + allocationQuantity;
  } else {
    // 未选择仓库：显示原库存
    return originalInventory;
  }
}

// 获取库存颜色
const getInventoryColor = (item: any) => {
  const finalInventory = calculateInventory(item);
  if (finalInventory === 0) {
    return '#f56c6c'; // 红色
  } else if (finalInventory < 10) {
    return '#e6a23c'; // 橙色
  } else {
    return '#67c23a'; // 绿色
  }
};
</script> 

<style scoped>
.mingxi-container {
  margin-top: 20px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  padding: 20px;
}

.mingxi-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.mingxi-header h3 {
  margin: 0;
  color: #303133;
  font-size: 16px;
  font-weight: 500;
}

.action-buttons {
  display: flex;
  gap: 10px;
}

.summary-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.summary-label {
  font-weight: 500;
  color: #303133;
}

.summary-stats {
  display: flex;
  gap: 20px;
}

.summary-stats span {
  color: #606266;
  font-size: 14px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  margin-top: 20px;
}

.search-area {
  margin-bottom: 15px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.pagination-container {
  margin-top: 15px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style> 